// app/service/schedule.js
const Service = require("egg").Service;
const schedule = require("node-schedule");

class ScheduleService extends Service {
  constructor(ctx) {
    super(ctx);
    this.SysJobLogService = ctx.service.monitor.sysJobLog;
    this.redis = ctx.service.tool.redis;
  }

  // 创建定时任务
  async create(name, cron, invoke_target, task) {
    // if (schedule.scheduledJobs[`${name}_job`]) {
    //   schedule.scheduledJobs[`${name}_job`].cancel();
    //   delete schedule.scheduledJobs[`${name}_job`];
    // }
    // schedule.scheduleJob(`${name}_job`, cron, async () => {
    //   let errCode = "";
    //   let res = "";
    //   try {
    //     res = await eval(`this.ctx.service.${invoke_target}`);
    //   } catch (error) {
    //     errCode = JSON.stringify(error);
    //   }
    //   await this.SysJobLogService.create({
    //     job_name: task.job_name,
    //     job_group: task.job_group,
    //     invoke_target: task.invoke_target,
    //     job_message: JSON.stringify(res),
    //     status: errCode ? "1" : "0",
    //     exception_info: errCode,
    //     create_time: new Date(),
    //   });
    // });
    // 创建或更新任务
    this.app.messenger.sendToAgent("scheduleOperation", {
      operation: "create", // 或 'update'
      name: name,
      time: cron,
      taskKey: task, // 用于在agent中识别执行哪个任务的键
    });
  }

  // 修改定时任务
  async update(name, newCron) {
    // if (schedule.scheduledJobs[`${name}_job`]) {
    //   schedule.scheduledJobs[`${name}_job`].reschedule(newCron);
    // }
    this.app.messenger.sendToAgent("scheduleOperation", {
      operation: "update",
      name,
      newCron,
    });
  }

  // 暂停定时任务
  async pause(name) {
    // this.ctx.logger.info(base.ctx.app.jobs[name]);
    // if (schedule.scheduledJobs[`${name}_job`]) {
    //   schedule.scheduledJobs[`${name}_job`].cancel();
    // }
    this.app.messenger.sendToAgent("scheduleOperation", {
      operation: "cancel",
      name,
    });
  }

  // 恢复定时任务
  async resume(name, cron) {
    // if (schedule.scheduledJobs[`${name}_job`]) {
    //   schedule.scheduledJobs[`${name}_job`].reschedule(cron);
    // } else {
    //   this.ctx.logger.warn(`Job ${name} does not exist.`);
    // }
    this.app.messenger.sendToAgent("scheduleOperation", {
      operation: "reschedule",
      name,
      cron,
    });
  }

  // 执行一次定时任务
  async runOnce(name, cron, task) {
    // if (schedule.scheduledJobs[`${name}_job`]) {
    //   schedule.scheduledJobs[`${name}_job`].invoke();
    // }
    this.app.messenger.sendToAgent("scheduleOperation", {
      operation: "invoke",
      name,
      time: cron,
      taskKey: task,
    });
  }

  // 获取所有的定时任务
  // async getAllJobs() {
  //   return this.app.jobs;
  // }
}

module.exports = ScheduleService;
